# -*- coding: utf-8 -*-
"""
配置管理模块
负责加载和解析配置文件
"""

import yaml
import os
from typing import Dict, Any, List


class Config:
    """配置管理类"""
    
    def __init__(self, config_path: str = None):
        """
        初始化配置
        
        Args:
            config_path: 配置文件路径，默认为 config/config.yaml
        """
        if config_path is None:
            # 获取项目根目录
            base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            config_path = os.path.join(base_dir, 'config', 'config.yaml')
        
        self.config_path = config_path
        self._config = self._load_config()
    
    def _load_config(self) -> Dict[str, Any]:
        """加载配置文件"""
        try:
            with open(self.config_path, 'r', encoding='utf-8') as f:
                return yaml.safe_load(f)
        except FileNotFoundError:
            raise FileNotFoundError(f"配置文件不存在: {self.config_path}")
        except yaml.YAMLError as e:
            raise ValueError(f"配置文件格式错误: {e}")
    
    def get(self, key: str, default: Any = None) -> Any:
        """
        获取配置项
        
        Args:
            key: 配置键，支持点号分隔的多级键，如 'mysql.host'
            default: 默认值
        
        Returns:
            配置值
        """
        keys = key.split('.')
        value = self._config
        
        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            else:
                return default
        
        return value
    
    # MySQL配置
    @property
    def mysql_host(self) -> str:
        return self.get('mysql.host', 'localhost')
    
    @property
    def mysql_port(self) -> int:
        return self.get('mysql.port', 3306)
    
    @property
    def mysql_database(self) -> str:
        return self.get('mysql.database', 'hive_metastore')
    
    @property
    def mysql_user(self) -> str:
        return self.get('mysql.user', 'root')
    
    @property
    def mysql_password(self) -> str:
        return self.get('mysql.password', '')
    
    @property
    def mysql_pool_size(self) -> int:
        return self.get('mysql.pool_size', 5)
    
    # Binlog配置
    @property
    def binlog_server_id(self) -> int:
        return self.get('binlog.server_id', 100)
    
    @property
    def binlog_slave_uuid(self) -> str:
        return self.get('binlog.slave_uuid', 'monitor-slave-001')
    
    # 监控配置
    @property
    def monitor_interval(self) -> int:
        return self.get('monitor.interval', 30)
    
    @property
    def monitor_mode(self) -> str:
        return self.get('monitor.mode', 'metadata')
    
    # 告警规则配置
    def get_alert_rule(self, rule_name: str) -> Dict[str, Any]:
        """获取告警规则配置"""
        return self.get(f'alert_rules.{rule_name}', {})
    
    # 飞书配置
    @property
    def feishu_webhook_url(self) -> str:
        return self.get('feishu.webhook_url', '')
    
    @property
    def feishu_at_users(self) -> Dict[str, List[str]]:
        return self.get('feishu.at_users', {})
    
    @property
    def feishu_dedup_window(self) -> int:
        return self.get('feishu.dedup_window', 300)
    
    @property
    def feishu_aggregate_window(self) -> int:
        return self.get('feishu.aggregate_window', 60)
    
    @property
    def feishu_silent_periods(self) -> List[Dict[str, str]]:
        return self.get('feishu.silent_periods', [])
    
    # 日志配置
    @property
    def log_level(self) -> str:
        return self.get('logging.level', 'INFO')
    
    @property
    def log_file(self) -> str:
        return self.get('logging.file', '/var/log/hive-metadata-monitor/monitor.log')
    
    @property
    def log_max_size(self) -> str:
        return self.get('logging.max_size', '100MB')
    
    @property
    def log_backup_count(self) -> int:
        return self.get('logging.backup_count', 10)


# 全局配置实例
config = Config()

